<?php

namespace App\Http\Controllers\Blog;

use App\Http\Controllers\Controller;
use App\Http\Requests\PostPageRequest;
use App\Http\Responses\Response;
use App\Models\Post;
use Illuminate\Http\JsonResponse;

class PostController extends Controller
{
    public function listByPage(PostPageRequest $request): JsonResponse
    {
        $paginator = Post::with(["tags", "category"])->orderby("post_update_time")->paginate($request->validated()["size"]);
        return Response::select_one($paginator);
    }

    public function findById($id): JsonResponse
    {
        if(Post::where("post_id", $id)->count() <= 0){
            return Response::not_found();
        }
        $post = Post::with(["detail", "category", "tags"])->find($id);
        $next_post = Post::with(["category", "tags"])->orderBy("post_update_time")->firstWhere("post_update_time", ">", $post->post_update_time);
        $prev_post = Post::with(["category", "tags"])->orderBy("post_update_time", "desc")->firstWhere("post_update_time", "<", $post->post_update_time);
        $post->next = $next_post;
        $post->prev = $prev_post;
        return Response::select_one($post);
    }
}
